package cn.gd.utils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;

public class EncryptionUtil {
    // 比较加密后的值是否相等
    public static Boolean verifyPassword(String password, String hashedPasswordFromDB) throws NoSuchAlgorithmException {
        MessageDigest md = MessageDigest.getInstance("SHA-256");
        byte[] inputHashBytes = md.digest(password.getBytes());
        byte[] storedHashBytes = Base64.getDecoder().decode(hashedPasswordFromDB);
        // 比较两个字节数组是否相等，以此判断密码是否正确
        return MessageDigest.isEqual(inputHashBytes, storedHashBytes);
    }

    // 对密码加密
    public static String hashPassword(String password) throws NoSuchAlgorithmException {
        MessageDigest md = MessageDigest.getInstance("SHA-256");
        byte[] hashBytes = md.digest(password.getBytes());
        // 将字节数组转换为Base64编码的字符串，方便存储和后续比较
        return Base64.getEncoder().encodeToString(hashBytes);
    }
}
